package com.chenju.easyshotjava.core;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WordUtils {

    public static List<String> getTestCaseIds(FileInputStream fis) {
        List<String> testCaseIds = new ArrayList<>();
        try {
            XWPFDocument doc = new XWPFDocument(fis);
            for (XWPFParagraph paragraph : doc.getParagraphs()) {
                if (isTestCaseParagraph(paragraph)) {
                    String caseId = extractCaseCodeFromTestCaseParagraph(paragraph);
                    if (caseId != null && !caseId.trim().isEmpty()) {
                        testCaseIds.add(caseId.trim());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return testCaseIds;
        }
        return testCaseIds;
    }

    /**
     * 添加图片到 Word 文档，保持原图比例，并自动调整到指定宽度
     * @param imagePath  图片路径
     * @param targetWidthInInches 图片目标宽度（英寸）
     */
    public static void addPictureToTestCase(XWPFRun imgRun, String imagePath, FileInputStream is, double targetWidthInInches) throws IOException, InvalidFormatException {
        // 读取图片的原始宽高
        BufferedImage img = ImageIO.read(new File(imagePath));
        int imgWidth = img.getWidth();
        int imgHeight = img.getHeight();

        // 转换目标宽度为 EMU
        int targetWidthEMU = Units.toEMU(targetWidthInInches);

        // 根据目标宽度计算高度以保持比例
        double aspectRatio = (double) imgHeight / imgWidth;
        int targetHeightEMU = (int) (targetWidthEMU * aspectRatio);

        // 插入图片到 Word 文档
        imgRun.addPicture(
                is,
                XWPFDocument.PICTURE_TYPE_PNG,
                imagePath,
                targetWidthEMU,
                targetHeightEMU
        );
    }

    /**
     * 生成报告，使用输入模板为”input.docx“
     * 考虑使用code模式导入
     */
    public void generateReportFromInputDocx(XWPFDocument doc) {
        try {
            List<File> images = new ArrayList<>();
            for (XWPFParagraph paragraph : doc.getParagraphs()) {
                String text = paragraph.getText().trim();

                if (isTestCaseParagraph(paragraph)) {
                    int imageIndex = 1;
                    while (true) {
                        String imagePath = extractCaseCodeFromTestCaseParagraph(paragraph) + "-" + String.format("%03d", imageIndex) + ".png";
                        File imgFile = new File(imagePath);
                        if (imgFile.exists()){
                            images.add(imgFile);
                        } else  {
                            break; // 如果文件不存在，停止查找更多图片
                        }
                        imageIndex++;
                    }
                }
                if (text.equals("测试截图：")) { // 找到“测试截图：”段落
                    addPicturesToTestScreenShot(paragraph, images);
                    images = new ArrayList<>();
                }
            }

            try (FileOutputStream out = new FileOutputStream("output.docx")) {
                doc.write(out);
            }
            JOptionPane.showMessageDialog(null, "报告已生成：" + "output.docx");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入截图到”测试截图：“段落后面
     */
    public static void addPicturesToTestScreenShot(XWPFParagraph paragraph, List<File> images) throws Exception {
        if (images.isEmpty()){
            return;
        }
        for (File image : images) {
            // 插入段落并添加图片
            XWPFRun imgRun = paragraph.createRun();
            try (FileInputStream is = new FileInputStream(image)) {
                imgRun.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, image.getName(), Units.toEMU(400), Units.toEMU(300));
            }
        }
    }

    private static boolean isTestCaseParagraph(XWPFParagraph paragraph) {
        return "2".equals(paragraph.getStyle()) && paragraph.getText().trim().contains("_");
    }

    private static String extractCaseCodeFromTestCaseParagraph(XWPFParagraph paragraph){
        return paragraph.getText().trim().split("_")[0];
    }

    public static void createCustomStyle(XWPFDocument document, String styleId, String styleName) {
        // 获取或创建文档样式
        XWPFStyles styles = document.createStyles();

        // 创建段落样式
        CTStyle ctStyle = CTStyle.Factory.newInstance();
        ctStyle.setStyleId(styleId);

        // 设置样式名称
        CTString styleNameElement = CTString.Factory.newInstance();
        styleNameElement.setVal(styleName);
        ctStyle.setName(styleNameElement);

        // 设置字体样式
        CTRPr rPr = CTRPr.Factory.newInstance();
        CTFonts fonts = rPr.addNewRFonts(); // 添加字体配置
        fonts.setAscii("Arial");
        fonts.setHAnsi("Arial");

        // 设置加粗
        rPr.addNewB().setVal("1");

        // 设置字体大小
        CTHpsMeasure size = rPr.addNewSz(); // 添加字体大小
        size.setVal(28); // 字体大小 14pt (1/2 pt)

        ctStyle.setRPr(rPr);

        // 添加样式到文档
        styles.addStyle(new XWPFStyle(ctStyle));
    }
}

